package org.wattdepot.cli.commands;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.UserCommandInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClientException;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Creates a chart from power generated or consumed.
 * 
 * @author Jarret Mizo, Shaun Ramento
 * 
 */
public class ChartPower extends UserCommandInterface implements UserCommands {

  /**
   * Prints information about a single source.
   * 
   * @param args arguments from command line.
   * @return output prints out the result of ChartPower.
   */
  public String doCommand(String args) {
    String[] inputString = args.split(" ");
    String output = null;
    try {
      output =
          chartPower(inputString[2], inputString[3], inputString[4], inputString[5],
              inputString[7], inputString[9]);
    }
    catch (WattDepotClientException e) {
      System.out.println("Chart power generated error.");
    }
    return output;
  }

  /**
   * Writes out an HTML file that when displayed in a browser will show a chart representation of
   * the power generated (or consumed) by this source from startday to endday, where data points are
   * generated at a sampling interval of minutes.
   * 
   * @param power The desired type of power the user wants to view, either "generated" or "consumed"
   * @param sourceName of one of the public sources is the system
   * @param startday Date of desired start day YYYY-MM-DD
   * @param endday Date of desired end day YYYY-MM-DD
   * @param minutes The Sample-interval time in minutes
   * @param file Name of the file that information will be written to
   * @return directory returns where the file is located
   * @throws WattDepotClientException throws exception
   */
  public String chartPower(String power, String sourceName, String startday, String endday,
      String minutes, String file) throws WattDepotClientException {
    StringBuffer directory = new StringBuffer(256);
    int interval = Integer.parseInt(minutes);
    ValidateDay day = new ValidateDay();
    XMLGregorianCalendar startTime = day.validateDay(startday);
    XMLGregorianCalendar endTime = day.validateDay(endday);
    int fileLength = file.length();
    String htmlExtension = file.substring(fileLength - 4, fileLength);
    System.out.println(verifyStartEndDate(startTime, endTime));
    if (!(verifyStartEndDate(startTime, endTime))) {
      directory.append("The initial day must be earlier than the final day\n");
      return directory.toString();
    }
    try {

      // when the power string is generated

      if (power.equalsIgnoreCase("generated") && htmlExtension.equalsIgnoreCase("html")) {
        FileWriter outputFile = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(outputFile);

        StringBuffer buffer = new StringBuffer();
        // beginning part of html file
        String beginPart =
            "<html>\n  <body>\n  "
                + "<img src=http://chart.apis.google.com/chart?chs=250x100&cht=lc&chd=t:";
        buffer.append(beginPart);
        while (!(Tstamp.equal(startTime, endTime))) {
          double powerGenerated = getClient().getPowerGenerated(sourceName, startTime) / 100000000;
          buffer.append(powerGenerated);
          buffer.append(',');
          startTime = Tstamp.incrementMinutes(startTime, interval);
        }

        // removes the last comma
        buffer.deleteCharAt(buffer.length() - 1);
        // end part of the html file
        String endPart = "&chds=0.0,25.0&chxt=y&chxr=0,0.0,25.0>\n    </body>\n</html>";
        buffer.append(endPart);
        // outputs the buffer string into the html file
        out.write(buffer.toString());
        out.close();
        // end of html file
        directory.append("Wrote: " + System.getProperty("user.dir") + "\\" + file);

      }
      // when the power string is consumed
      else if (power.equalsIgnoreCase("consumed")) {
        FileWriter outputFile = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(outputFile);

        StringBuffer buffer = new StringBuffer();
        // beginning part of html file
        String beginPart =
            "<html>\n  <body>\n  "
                + "<img src=http://chart.apis.google.com/chart?chs=250x100&cht=lc&chd=t:";
        buffer.append(beginPart);
        while (!(Tstamp.equal(startTime, endTime))) {
          double powerConsumed = getClient().getPowerConsumed(sourceName, startTime) / 100000000;
          buffer.append(powerConsumed);
          buffer.append(',');
          startTime = Tstamp.incrementMinutes(startTime, interval);
        }

        // removes the last comma
        buffer.deleteCharAt(buffer.length() - 1);
        // end part of the html file
        String endPart = "&chds=0.0,25.0&chxt=y&chxr=0,0.0,25.0>\n    </body>\n</html>";
        buffer.append(endPart);
        // outputs the buffer string into the html file
        out.write(buffer.toString());
        out.close();
        // end of html file
        directory.append("Wrote: " + System.getProperty("user.dir") + "\\" + file);
      }

      else {
        directory.append("The extension file must be in html.");
      }

    }
    catch (IOException e) {
      e.printStackTrace();
    }
    catch (NotAuthorizedException e) {
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      e.printStackTrace();
    }
    catch (BadXmlException e) {
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      e.printStackTrace();
    }

    return directory.toString();
  }

  /**
   * Verifies if start day is earlier than end day.
   * 
   * @param startDay arguments from command line.
   * @param endDay arguments from command line.
   * @return true if startDay is earlier than endDay.
   */
  public Boolean verifyStartEndDate(XMLGregorianCalendar startDay, XMLGregorianCalendar endDay) {
    if (Tstamp.lessThan(startDay, endDay)) {
      return true;
    }
    return false;
  }

}
